package com.carleasoft.mps.cms.business.resource.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.cms.business.article.constants.ExceptionCMSEnum;
import com.carleasoft.mps.cms.business.article.service.ArticleService;
import com.carleasoft.mps.cms.business.clerk.bean.DealProcessEntity;
import com.carleasoft.mps.cms.business.clerk.service.DealProcessService;
import com.carleasoft.mps.cms.business.collector.bean.entity.CollectorEntity;
import com.carleasoft.mps.cms.business.collector.service.CollectorService;
import com.carleasoft.mps.cms.business.resource.bean.entity.LibraryEntity;
import com.carleasoft.mps.cms.business.resource.bean.entity.ReasourceCollectEntity;
import com.carleasoft.mps.cms.business.resource.bean.entity.ReasourceEntity;
import com.carleasoft.mps.cms.business.resource.bean.entity.ReasourceOpenEntity;
import com.carleasoft.mps.cms.business.resource.bean.po.DoorPagePo;
import com.carleasoft.mps.cms.business.resource.bean.po.ReasourcePageQueryPo;
import com.carleasoft.mps.cms.business.resource.bean.po.ReasourcePo;
import com.carleasoft.mps.cms.business.resource.bean.po.ResourcePo;
import com.carleasoft.mps.cms.business.resource.bean.vo.*;
import com.carleasoft.mps.cms.business.resource.constans.LibraryEnum;
import com.carleasoft.mps.cms.business.resource.dao.ReasourceMapper;
import com.carleasoft.mps.cms.business.resource.service.LibraryService;
import com.carleasoft.mps.cms.business.resource.service.ReasourceCollectService;
import com.carleasoft.mps.cms.business.resource.service.ReasourceOpenService;
import com.carleasoft.mps.cms.business.resource.service.ReasourceService;
import com.carleasoft.mps.cms.business.user.bean.UserSkill;
import com.carleasoft.mps.cms.business.user.service.UserSkillService;
import com.carleasoft.mps.cms.business.write.bean.vo.UserListVos;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.user.UserDeptVo;
import com.carleasoft.mps.core.user.UserPro;
import com.carleasoft.mps.core.utils.IBeanUtil;
import com.carleasoft.mps.core.utils.IpUtils;
import com.carleasoft.mps.excel.utils.ConvertTemplatePath;
import com.carleasoft.mps.excel.utils.ExcelUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: yangHao
 * @createDate:2023/5/18
 * @description:
 */
@Service
public class ReasourceServiceImpl extends ServiceImpl<ReasourceMapper, ReasourceEntity> implements ReasourceService {

    @Autowired
    private ReasourceCollectService reasourceCollectService;
    @Autowired
    private ReasourceOpenService reasourceOpenService;
    @Autowired
    private LibraryService libraryService;
    @Autowired
    private UserSkillService userSkillService;
    @Autowired
    private DealProcessService dealProcessService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CollectorService collectorService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveResource(ReasourcePo reasourcePo, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        String idStr = IdWorker.getIdStr();
        ReasourceEntity reasourceEntity = BeanUtil.copyProperties(reasourcePo, ReasourceEntity.class);
        reasourceEntity.setRName(reasourcePo.getName());
        reasourceEntity.setRType(reasourcePo.getType());
        reasourceEntity.setRCategory(reasourcePo.getCategory());
        reasourceEntity.setRLibrary(reasourcePo.getLibrary());
        reasourceEntity.setCreateTime(LocalDateTime.now());
        reasourceEntity.setCreatePersonCode(user.getUserCode());
        reasourceEntity.setCreatePersonName(user.getUserName());
        reasourceEntity.setUpdateTime(LocalDateTime.now());
        reasourceEntity.setUpdatePersonCode(user.getUserCode());
        reasourceEntity.setUpdatePersonName(user.getUserName());
        reasourceEntity.setReasourceCode(idStr);
        reasourceEntity.setIsTop(0);
        String ipAddr = IpUtils.getIpAddr(request);
        ReasourceOpenEntity reasourceOpenEntity = new ReasourceOpenEntity();
        reasourceOpenEntity.setReasourceCode(idStr);
        reasourceOpenEntity.setCreateTime(LocalDateTime.now());
        reasourceOpenEntity.setCreatePersonCode(user.getUserCode());
        reasourceOpenEntity.setCreatePersonName(user.getUserName());
        reasourceOpenEntity.setOpenType(3);
        reasourceOpenEntity.setIpAddress(ipAddr);
        reasourceOpenService.save(reasourceOpenEntity);
        return this.save(reasourceEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateResource(ReasourcePo reasourcePo, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        ReasourceEntity reasourceEntity = this.getOne(Wrappers.<ReasourceEntity>lambdaQuery()
                .eq(ReasourceEntity::getReasourceCode, reasourcePo.getReasourceCode()));
        if (Objects.isNull(reasourceEntity)) {
            throw new BusinessException(ExceptionCMSEnum.DATABASE_NO);
        }
        BeanUtil.copyProperties(reasourcePo, reasourceEntity);
        reasourceEntity.setRName(reasourcePo.getName());
        reasourceEntity.setRType(reasourcePo.getType());
        reasourceEntity.setRCategory(reasourcePo.getCategory());
        reasourceEntity.setRLibrary(reasourcePo.getLibrary());
        reasourceEntity.setUpdatePersonCode(user.getUserCode());
        reasourceEntity.setUpdatePersonName(user.getUserName());
        reasourceEntity.setUpdateTime(LocalDateTime.now());
        reasourceOpenService.remove(Wrappers.<ReasourceOpenEntity>lambdaQuery().eq(ReasourceOpenEntity::getReasourceCode, reasourcePo.getReasourceCode())
                .eq(ReasourceOpenEntity::getOpenType, 3));
        // 获取ip地址
        String ipAddr = IpUtils.getIpAddr(request);
        ReasourceOpenEntity reasourceOpenEntity = new ReasourceOpenEntity();
        reasourceOpenEntity.setReasourceCode(reasourcePo.getReasourceCode());
        reasourceOpenEntity.setCreateTime(LocalDateTime.now());
        reasourceOpenEntity.setCreatePersonCode(user.getUserCode());
        reasourceOpenEntity.setCreatePersonName(user.getUserName());
        reasourceOpenEntity.setOpenType(3);
        reasourceOpenEntity.setIpAddress(ipAddr);
        reasourceOpenService.save(reasourceOpenEntity);
        return this.updateById(reasourceEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean top(ReasourcePo reasourcePo) {
        return this.update(Wrappers.<ReasourceEntity>lambdaUpdate()
                .eq(ReasourceEntity::getReasourceCode, reasourcePo.getReasourceCode())
                .set(ReasourceEntity::getIsTop, reasourcePo.getTopType()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(ReasourcePo reasourcePo) {
        reasourceOpenService.remove(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                .eq(ReasourceOpenEntity::getReasourceCode, reasourcePo.getReasourceCode()));
        return this.remove(Wrappers.<ReasourceEntity>lambdaQuery()
                .eq(ReasourceEntity::getReasourceCode, reasourcePo.getReasourceCode()));
    }

    @Override
    public ReasourceVo detail(ReasourcePo reasourcePo) {
        IBeanUtil.paramVerify(reasourcePo, "resource");
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        ReasourceEntity reasourceEntity = this.getOne(Wrappers.<ReasourceEntity>lambdaQuery()
                .eq(ReasourceEntity::getReasourceCode, reasourcePo.getReasourceCode()));
        if (Objects.isNull(reasourceEntity)) {
            throw new BusinessException(ExceptionCMSEnum.NO_SOURCE_EXITS);
        }
        if (StrUtil.isNotBlank(reasourceEntity.getContent()) && reasourceEntity.getRType().equals(5) && reasourcePo.getIsDoor()) {
            String html = reasourceEntity.getContent();
            Document doc = Jsoup.parse(html);
            Elements imgs = doc.select("img");
            if (imgs.size() > 0) {
                for (int i = 0; i < imgs.size(); i++) {
                    Element img = imgs.get(i);
                    String fileName = img.attr("alt");
                    String style = null;
                    String attr = img.attr("style");
                    if (StringUtils.isBlank(attr)) {
                        style = "width: 200px; height: 200px";
                    } else {
                        style = img.attr("style");
                    }
                    String result = "<ArmyImg fileName=\"" + fileName + "\" style=\"" + style + "\"></ArmyImg>";

                    if (html.contains(fileName)) {
                        html = html.replaceFirst("<img[^>]+>", result);
                    }
                }
                reasourceEntity.setContent(html);
            }
        }
        if (Objects.nonNull(user) && user.getUserCode()!=null){
            if (!(user.getUserCode().equals(reasourceEntity.getCreatePersonCode()) || user.getUserCat() == 3 || user.getUserCat() == 1)) {
                if (StrUtil.isNotBlank(reasourceEntity.getPermission()) && reasourcePo.getResource() == 2) {
                    if (reasourceEntity.getPermission().equals("[]")) {

                    } else {
                        String permission = reasourceEntity.getPermission();
                        List<String> list = JSONObject.parseArray(permission, String.class);
                        int aaa = 0;
                        for (UserPro userPro : user.getUserPros()) {
                            for (UserDeptVo userDeptVo : userPro.getUserDeptVoList()) {
                                if (list.contains(userDeptVo.getDeptCode())) {
                                    aaa = 1;
                                    break;
                                }

                            }
                        }
                        if (aaa == 0) {
                            throw new BusinessException(ExceptionCMSEnum.NO_PERMISSION);
                        }
                    }

                }
            }
        }



        ReasourceVo reasourceVo = BeanUtil.copyProperties(reasourceEntity, ReasourceVo.class);
        reasourceVo.setCategory(reasourceEntity.getRCategory());
        reasourceVo.setCategoryName(reasourceCollectService.getOne(Wrappers.<ReasourceCollectEntity>lambdaQuery()
                .eq(ReasourceCollectEntity::getCategoryCode, reasourceEntity.getRCategory())).getCategoryName());
        reasourceVo.setName(reasourceEntity.getRName());
        reasourceVo.setLibrary(reasourceEntity.getRLibrary());
        LibraryEntity libraryServiceOne = libraryService.getOne(Wrappers.<LibraryEntity>lambdaQuery()
                .eq(LibraryEntity::getLibraryCode, reasourceEntity.getRLibrary()));
        reasourceVo.setLibraryName(libraryServiceOne.getLibraryName());
        reasourceVo.setType(reasourceEntity.getRType());
        if (Objects.nonNull(user) && user.getUserCode() != null) {
            List<ReasourceOpenEntity> openEntities = reasourceOpenService.list(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                    .eq(ReasourceOpenEntity::getReasourceCode, reasourcePo.getReasourceCode())
                    .eq(ReasourceOpenEntity::getCreatePersonCode, user.getUserCode())
                    .eq(ReasourceOpenEntity::getOpenType, 4));
            if (CollUtil.isNotEmpty(openEntities)) {
                reasourceVo.setCollect(1);
            } else {
                reasourceVo.setCollect(2);
            }
        }

        List<ReasourceOpenEntity> reasourceOpenEntities = reasourceOpenService.list(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                .eq(ReasourceOpenEntity::getReasourceCode, reasourceEntity.getReasourceCode()));
        Map<Integer, List<ReasourceOpenEntity>> map = reasourceOpenEntities.stream().collect(Collectors.groupingBy(ReasourceOpenEntity::getOpenType));
        if (map.containsKey(1)) {
            reasourceVo.setDownloads(map.get(1).size());
        }
        if (map.containsKey(4)) {
            reasourceVo.setCollector(map.get(4).size());
        }
        if (map.containsKey(2)) {
            reasourceVo.setView(map.get(2).size());
        }
        //判断当前用户是否收藏了该资源信息
        if(StringUtils.isNotBlank(user.getUserCode())){
            ReasourceOpenEntity reasourceOpenServiceOne = reasourceOpenService.getOne(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                    .eq(ReasourceOpenEntity::getReasourceCode, reasourceEntity.getReasourceCode())
                    .eq(ReasourceOpenEntity::getCreatePersonCode,user.getUserCode())
                    .eq(ReasourceOpenEntity::getOpenType,4));
            if(Objects.isNull(reasourceOpenServiceOne)){
                reasourceVo.setCollect(2);
            }else {
                reasourceVo.setCollect(1);
            }
        }

        return reasourceVo;
    }

    @Override
    public Page<ReasourcePageQueryVo> doorPageQuery(Page page, ReasourcePageQueryPo reasourcePageQueryPo, HttpServletRequest request) {
        if (StrUtil.isNotBlank(reasourcePageQueryPo.getLibraryCode())) {
            reasourcePageQueryPo.setLibrary(reasourcePageQueryPo.getLibraryCode());
        }
        Page<ReasourcePageQueryVo> reasourcePageQueryVoPage = this.getBaseMapper().doorPageQuery(page, reasourcePageQueryPo);
        if (CollUtil.isNotEmpty(reasourcePageQueryVoPage.getRecords())) {
            List<String> reasourceCodes = reasourcePageQueryVoPage.getRecords().stream().map(ReasourcePageQueryVo::getReasourceCode).collect(Collectors.toList());
            List<ReasourceOpenEntity> reasourceOpenEntities = reasourceOpenService.list(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                    .in(ReasourceOpenEntity::getReasourceCode, reasourceCodes));
            Map<String, List<ReasourceOpenEntity>> listMap = reasourceOpenEntities.stream().collect(Collectors.groupingBy(ReasourceOpenEntity::getReasourceCode));
            List<String> codes = reasourcePageQueryVoPage.getRecords().stream().map(ReasourcePageQueryVo::getCategory).filter(Objects::nonNull).collect(Collectors.toList());
            List<ReasourceCollectEntity> reasourceCollectEntities = reasourceCollectService.list(Wrappers.<ReasourceCollectEntity>lambdaQuery()
                    .in(ReasourceCollectEntity::getCategoryCode, codes));
            Map<String, ReasourceCollectEntity> map = reasourceCollectEntities.stream().collect(Collectors.toMap(ReasourceCollectEntity::getCategoryCode, Function.identity()));
            Set<String> libraryCodes = reasourcePageQueryVoPage.getRecords().stream().map(ReasourcePageQueryVo::getLibrary).collect(Collectors.toSet());
            List<LibraryEntity> entities = libraryService.list(Wrappers.<LibraryEntity>lambdaQuery()
                    .in(LibraryEntity::getLibraryCode, libraryCodes));
            Map<String, LibraryEntity> entityMap = entities.stream().collect(Collectors.toMap(LibraryEntity::getLibraryCode, Function.identity()));
            for (ReasourcePageQueryVo record : reasourcePageQueryVoPage.getRecords()) {
                if (entityMap.containsKey(record.getLibrary())) {
                    record.setLibraryName(entityMap.get(record.getLibrary()).getLibraryName());
                }
                if (map.containsKey(record.getCategory())) {
                    record.setCategoryName(map.get(record.getCategory()).getCategoryName());
                }
                if (listMap.containsKey(record.getReasourceCode())) {
                    List<ReasourceOpenEntity> openEntities = listMap.get(record.getReasourceCode());
                    Map<Integer, List<ReasourceOpenEntity>> integerListMap = openEntities.stream().collect(Collectors.groupingBy(ReasourceOpenEntity::getOpenType));
                    if (integerListMap.containsKey(2)) {
                        record.setView(integerListMap.get(2).size());
                    }
                    if (integerListMap.containsKey(4)) {
                        record.setCollector(integerListMap.get(4).size());
                    }
                }
            }
        }
        return reasourcePageQueryVoPage;
    }

    @Override
    public List<LibraryEntity> getLibrary() {
        List<LibraryEntity> libraryEntities = libraryService.list(Wrappers.<LibraryEntity>lambdaQuery()
                .eq(LibraryEntity::getIsShow, 1));
        return libraryEntities;
    }

    @Override
    public List<ReasourceCollectEntity> getCategory(LibraryEntity reasourceEntity) {
        List<ReasourceCollectEntity> reasourceCollectEntities = reasourceCollectService.list(Wrappers.<ReasourceCollectEntity>lambdaQuery()
                .eq(ReasourceCollectEntity::getLibrary, reasourceEntity.getLibraryCode()));
        if (CollUtil.isNotEmpty(reasourceCollectEntities)) {
            List<String> categoryCodes = reasourceCollectEntities.stream().map(ReasourceCollectEntity::getCategoryCode).collect(Collectors.toList());
            List<ReasourceEntity> reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                    .in(ReasourceEntity::getRCategory, categoryCodes));
            Map<String, List<ReasourceEntity>> map = reasourceEntities.stream().collect(Collectors.groupingBy(ReasourceEntity::getRCategory));
            for (ReasourceCollectEntity reasourceCollectEntity : reasourceCollectEntities) {
                if (map.containsKey(reasourceCollectEntity.getCategoryCode())) {
                    reasourceCollectEntity.setSum(map.get(reasourceCollectEntity.getCategoryCode()).size());
                }
            }
        }

        return reasourceCollectEntities;
    }

    @Override
    public WorkbenchCountVo workbenchCount() {
        WorkbenchCountVo workbenchCountVo = new WorkbenchCountVo();
        int count = this.count();
        workbenchCountVo.setResource(count);
        workbenchCountVo.setTalents(userSkillService.count(Wrappers.<UserSkill>lambdaQuery()
                .eq(UserSkill::getIsDelete, 0)
                .eq(UserSkill::getUserType, 1)));
        int i = dealProcessService.count(Wrappers.<DealProcessEntity>lambdaQuery()
                .eq(DealProcessEntity::getState, 1)
                .eq(DealProcessEntity::getIsDelete, 0));
        workbenchCountVo.setClerk(i);
        String categoryCode = "aedd68de17c14803b0a9d8111f5fcb0e";
        int aaa = articleService.count(categoryCode);
        workbenchCountVo.setLaw(aaa);
        String code = "78ebbb38c93944baa47cc829695717c5";
        int bbb = articleService.count(code);
        workbenchCountVo.setPsychology(bbb);
        return workbenchCountVo;
    }

    @Override
    public List<WebCountVo> webCount() {
        List<WebCountVo> webCountVos = new ArrayList<>();
        List<LibraryEntity> libraryEntities = libraryService.list();
        if (CollUtil.isNotEmpty(libraryEntities)) {
            Map<String, List<ReasourceEntity>> map = new HashMap<>();
            List<String> libraryCodes = libraryEntities.stream().map(LibraryEntity::getLibraryCode).collect(Collectors.toList());
            List<ReasourceEntity> reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                    .in(ReasourceEntity::getRLibrary, libraryCodes));
            if (CollUtil.isNotEmpty(reasourceEntities)) {
                map = reasourceEntities.stream().collect(Collectors.groupingBy(ReasourceEntity::getRLibrary));
            }
            for (LibraryEntity libraryEntity : libraryEntities) {
                if (libraryEntity.getIsShow().equals(1)) {
                    WebCountVo webCountVo = new WebCountVo();
                    webCountVo.setName(libraryEntity.getLibraryName());
                    if (map.containsKey(libraryEntity.getLibraryCode())) {
                        webCountVo.setSum(map.get(libraryEntity.getLibraryCode()).size());
                    }
                    webCountVos.add(webCountVo);
                }

            }
        }

        return webCountVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(ResourcePo resourcePo, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        List<ReasourceEntity> reasourceEntities = new ArrayList<>();
        List<ReasourceExcelVo> suppliesInformationVos = new ArrayList<>();
        if (StrUtil.isNotBlank(resourcePo.getCode())) {
            reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                    .eq(ReasourceEntity::getRLibrary, resourcePo.getCode()));
        } else {
            reasourceEntities = this.list();
        }
        if (CollUtil.isNotEmpty(reasourceEntities)) {
            List<LibraryEntity> libraryEntities = libraryService.list();
            Map<String, LibraryEntity> entityMap = new HashMap<>();
            if (CollUtil.isNotEmpty(libraryEntities)) {
                entityMap = libraryEntities.stream().collect(Collectors.toMap(LibraryEntity::getLibraryCode, Function.identity()));
            }
            List<ReasourceCollectEntity> reasourceCollectEntities = reasourceCollectService.list();
            Map<String, ReasourceCollectEntity> collectEntityMap = new HashMap<>();
            if (CollUtil.isNotEmpty(reasourceCollectEntities)) {
                collectEntityMap = reasourceCollectEntities.stream().collect(Collectors.toMap(ReasourceCollectEntity::getCategoryCode, Function.identity()));
            }
            for (ReasourceEntity reasourceEntity : reasourceEntities) {
                ReasourceExcelVo reasourceExcelVo = new ReasourceExcelVo();
                reasourceExcelVo.setName(reasourceEntity.getRName());
                if (entityMap.containsKey(reasourceEntity.getRLibrary())) {
                    reasourceExcelVo.setLibrary(entityMap.get(reasourceEntity.getRLibrary()).getLibraryName());
                }
                if (collectEntityMap.containsKey(reasourceEntity.getRCategory())){
                    reasourceExcelVo.setCategory(collectEntityMap.get(reasourceEntity.getRCategory()).getCategoryName());
                }
                reasourceExcelVo.setIntroduce(reasourceEntity.getIntroduce());
                suppliesInformationVos.add(reasourceExcelVo);
            }
            map.put("list", suppliesInformationVos);
        }
        String path = "\\templates\\resourceTmplace.xls";
        TemplateExportParams templatePath = new TemplateExportParams(ConvertTemplatePath.convertTemplatePath(path));
        try {
            String fileName="资源八库";
            ExcelUtils.exportExcel(templatePath, map, fileName, response);
//            ExcelUtils.exportExcel(templatePath, map, "", response);
        } catch (IOException e) {
            throw new BusinessException(ExceptionCMSEnum.NO_SOURCE_EXITS);
        }
        return true;
    }


    @Override
    public Page<ReasourcePageQueryVo> pageQuery(Page page, ReasourcePageQueryPo reasourcePageQueryPo, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        reasourcePageQueryPo.setUserCode(user.getUserCode());
        Page<ReasourcePageQueryVo> reasourcePageQueryVoPage = this.getBaseMapper().pageQuery(page, reasourcePageQueryPo);
        if (CollUtil.isNotEmpty(reasourcePageQueryVoPage.getRecords())) {
            List<String> codes = reasourcePageQueryVoPage.getRecords().stream().map(ReasourcePageQueryVo::getCategory).filter(Objects::nonNull).collect(Collectors.toList());
            List<ReasourceCollectEntity> reasourceCollectEntities = reasourceCollectService.list(Wrappers.<ReasourceCollectEntity>lambdaQuery()
                    .in(ReasourceCollectEntity::getCategoryCode, codes));
            Map<String, ReasourceCollectEntity> map = reasourceCollectEntities.stream().collect(Collectors.toMap(ReasourceCollectEntity::getCategoryCode, Function.identity()));
            Set<String> libraryCodes = reasourcePageQueryVoPage.getRecords().stream().map(ReasourcePageQueryVo::getLibrary).collect(Collectors.toSet());
            List<LibraryEntity> entities = libraryService.list(Wrappers.<LibraryEntity>lambdaQuery()
                    .in(LibraryEntity::getLibraryCode, libraryCodes));
            Map<String, LibraryEntity> entityMap = entities.stream().collect(Collectors.toMap(LibraryEntity::getLibraryCode, Function.identity()));
            for (ReasourcePageQueryVo record : reasourcePageQueryVoPage.getRecords()) {
                if (entityMap.containsKey(record.getLibrary())) {
                    record.setLibraryName(entityMap.get(record.getLibrary()).getLibraryName());
                }
                if (map.containsKey(record.getCategory())) {
                    record.setCategoryName(map.get(record.getCategory()).getCategoryName());
                }
            }
        }
        return reasourcePageQueryVoPage;
    }

    @Override
    public List<CategoryVo> getLibraryByCategory(ReasourcePo reasourcePo) {
        List<CategoryVo> categoryVos = new ArrayList<>();
        List<ReasourceCollectEntity> entities = reasourceCollectService.list(Wrappers.<ReasourceCollectEntity>lambdaQuery()
                .eq(ReasourceCollectEntity::getLibrary, reasourcePo.getLibrary()));
        if (CollUtil.isNotEmpty(entities)) {
            List<String> categoryCodes = entities.stream().map(ReasourceCollectEntity::getCategoryCode).collect(Collectors.toList());
            List<ReasourceEntity> reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                    .in(ReasourceEntity::getRCategory, categoryCodes));
            Map<String, List<ReasourceEntity>> map = new HashMap<>();
            if (CollUtil.isNotEmpty(reasourceEntities)) {
                map = reasourceEntities.stream().collect(Collectors.groupingBy(ReasourceEntity::getRCategory));
            }
            for (ReasourceCollectEntity entity : entities) {
                CategoryVo categoryVo = new CategoryVo();
                categoryVo.setCategoryCode(entity.getCategoryCode());
                categoryVo.setCategoryName(entity.getCategoryName());
                if (map.containsKey(entity.getCategoryCode())) {
                    categoryVo.setSum(map.get(entity.getCategoryCode()).size());
                } else {
                    categoryVo.setSum(0);
                }
                categoryVos.add(categoryVo);
            }
        }
        return categoryVos;
    }

    @Override
    public List<DoorListVo> doorList(DoorPagePo doorPagePo) {
        List<DoorListVo> doorListVos = new ArrayList<>();
        List<ReasourceEntity> reasourceEntities = new ArrayList<>();
        List<LibraryEntity> libraryEntities = libraryService.list(Wrappers.<LibraryEntity>lambdaQuery()
                .eq(LibraryEntity::getIsShow, 1));
        if (CollUtil.isNotEmpty(libraryEntities)) {
            List<String> code = libraryEntities.stream().map(LibraryEntity::getLibraryCode).collect(Collectors.toList());
            if (doorPagePo.getType() == 1) {
                reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery().eq(ReasourceEntity::getIsTop, 1)
                        .in(ReasourceEntity::getRLibrary, code).orderByDesc(ReasourceEntity::getUpdateTime)
                );
            } else if (doorPagePo.getType() == 2) {
                reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                        .in(ReasourceEntity::getRLibrary, code).orderByDesc(ReasourceEntity::getUpdateTime)
                );
            } else if (doorPagePo.getType() == 3) {
                reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery().eq(ReasourceEntity::getRType, 2)
                        .in(ReasourceEntity::getRLibrary, code)

                        .orderByDesc(ReasourceEntity::getUpdateTime));
            } else if (doorPagePo.getType() == 4 || doorPagePo.getType() == 6) {
                reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                        .in(ReasourceEntity::getRLibrary, code)
                );
            } else if (doorPagePo.getType() == 5) {
                //1代表为一个月    正的往前  负的为后
                Date date = stepMonth(new Date(), -1);
                reasourceEntities = this.list(Wrappers.<ReasourceEntity>lambdaQuery()
                        .in(ReasourceEntity::getRLibrary, code)
                        .between(ReasourceEntity::getUpdateTime, date, new Date())
                        .orderByDesc(ReasourceEntity::getUpdateTime)
                );
            }
            if (CollUtil.isNotEmpty(reasourceEntities)) {
                List<String> resourceCodes = reasourceEntities.stream().map(ReasourceEntity::getReasourceCode).collect(Collectors.toList());
                List<ReasourceOpenEntity> reasourceOpenEntities = reasourceOpenService.list(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                        .in(ReasourceOpenEntity::getReasourceCode, resourceCodes));
                Map<String, List<ReasourceOpenEntity>> listMap = reasourceOpenEntities.stream().collect(Collectors.groupingBy(ReasourceOpenEntity::getReasourceCode));
                Set<String> codes = reasourceEntities.stream().map(ReasourceEntity::getRCategory).collect(Collectors.toSet());
                List<ReasourceCollectEntity> reasourceCollectEntities = reasourceCollectService.list(Wrappers.<ReasourceCollectEntity>lambdaQuery()
                        .in(ReasourceCollectEntity::getCategoryCode, codes));
                Map<String, ReasourceCollectEntity> map = reasourceCollectEntities.stream().collect(Collectors.toMap(ReasourceCollectEntity::getCategoryCode, Function.identity()));
                Set<String> libraryCodes = reasourceEntities.stream().map(ReasourceEntity::getRLibrary).collect(Collectors.toSet());
                List<LibraryEntity> entities = libraryService.list(Wrappers.<LibraryEntity>lambdaQuery()
                        .in(LibraryEntity::getLibraryCode, libraryCodes));
                Map<String, LibraryEntity> entityMap = entities.stream().collect(Collectors.toMap(LibraryEntity::getLibraryCode, Function.identity()));
                for (ReasourceEntity reasourceEntity : reasourceEntities) {
                    DoorListVo doorListVo = BeanUtil.copyProperties(reasourceEntity, DoorListVo.class);
                    doorListVo.setName(reasourceEntity.getRName());
                    if (map.containsKey(reasourceEntity.getRCategory())) {
                        doorListVo.setCategoryName(map.get(reasourceEntity.getRCategory()).getCategoryName());
                    }
                    if (entityMap.containsKey(reasourceEntity.getRLibrary())) {
                        doorListVo.setLibraryName(entityMap.get(reasourceEntity.getRLibrary()).getLibraryName());

                    }
                    if (listMap.containsKey(reasourceEntity.getReasourceCode())) {
                        List<ReasourceOpenEntity> openEntities = listMap.get(reasourceEntity.getReasourceCode());
                        Map<Integer, List<ReasourceOpenEntity>> integerListMap = openEntities.stream().collect(Collectors.groupingBy(ReasourceOpenEntity::getOpenType));
                        if (integerListMap.containsKey(1)) {
                            doorListVo.setDownloads(integerListMap.get(1).size());
                        }
                        if (integerListMap.containsKey(2)) {
                            doorListVo.setView(integerListMap.get(2).size());
                        }
                        if (integerListMap.containsKey(4)) {
                            doorListVo.setCollector(integerListMap.get(4).size());
                        }

                    }
                    doorListVos.add(doorListVo);
                }
                if (doorPagePo.getType() == 4 || doorPagePo.getType() == 5) {
                    if (CollUtil.isNotEmpty(doorListVos)) {
                        return doorListVos.stream().sorted(Comparator.comparing(DoorListVo::getView).reversed()).collect(Collectors.toList());
                    }
                }
                if (doorPagePo.getType() == 6) {
                    return doorListVos.stream().sorted(Comparator.comparing(DoorListVo::getCollector).reversed()).collect(Collectors.toList());
                }
            }
        }


        return doorListVos;
    }

    @Override
    public List<DoorLibraryVo> doorLibrary() {
        List<DoorLibraryVo> doorLibraryVos = new ArrayList<>();
        List<ReasourceEntity> reasourceEntities = this.list();
        Map<String, List<ReasourceEntity>> map = reasourceEntities.stream().collect(Collectors.groupingBy(ReasourceEntity::getRLibrary));
//        Set<String> libraryCodes = reasourceEntities.stream().map(ReasourceEntity::getRLibrary).collect(Collectors.toSet());
        List<LibraryEntity> libraryEntities = libraryService.list(Wrappers.<LibraryEntity>lambdaQuery()
                .eq(LibraryEntity::getIsShow, 1));
        for (LibraryEntity libraryEntity : libraryEntities) {
            DoorLibraryVo doorLibraryVo = new DoorLibraryVo();
            doorLibraryVo.setLibrary(libraryEntity.getLibraryCode());
            doorLibraryVo.setImage(libraryEntity.getImage());
            doorLibraryVo.setLibraryName(libraryEntity.getLibraryName());
            if (map.containsKey(libraryEntity.getLibraryCode())) {
                List<ReasourceEntity> entities = map.get(libraryEntity.getLibraryCode());
                List<ResourceVo> resourceVos = new ArrayList<>();
                entities.forEach(i -> {
                    resourceVos.add(BeanUtil.copyProperties(i, ResourceVo.class));
                });
                doorLibraryVo.setResourceList(resourceVos);
            }
            doorLibraryVos.add(doorLibraryVo);
        }
        return doorLibraryVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean viewDetail(ReasourcePo reasourcePo, HttpServletRequest request) {
        boolean isOk = false;
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        int aaa = 0;
        if (reasourcePo.getOpenType() != 5) {
            if (reasourcePo.getOpenType() == 4 || reasourcePo.getOpenType() == 1) {
                ReasourceOpenEntity reasourceOpenServiceOne = reasourceOpenService.getOne(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                        .eq(ReasourceOpenEntity::getReasourceCode, reasourcePo.getReasourceCode())
                        .eq(ReasourceOpenEntity::getCreatePersonCode, user.getUserCode())
                        .eq(ReasourceOpenEntity::getOpenType, reasourcePo.getOpenType()));
                if (Objects.nonNull(reasourceOpenServiceOne)) {
                    aaa = 1;
                }
            }
            if (aaa == 0) {
                ReasourceOpenEntity reasourceOpenEntity = new ReasourceOpenEntity();
                reasourceOpenEntity.setReasourceCode(reasourcePo.getReasourceCode());
                reasourceOpenEntity.setIpAddress(IpUtils.getIpAddr(request));
                reasourceOpenEntity.setCreateTime(LocalDateTime.now());
                reasourceOpenEntity.setCreatePersonCode(user.getUserCode());
                reasourceOpenEntity.setCreatePersonName(user.getUserName());
                reasourceOpenEntity.setOpenType(reasourcePo.getOpenType());
                isOk = reasourceOpenService.save(reasourceOpenEntity);
            }

        } else {
            ReasourceOpenEntity reasourceOpenServiceOne = reasourceOpenService.getOne(Wrappers.<ReasourceOpenEntity>lambdaQuery()
                    .eq(ReasourceOpenEntity::getReasourceCode, reasourcePo.getReasourceCode())
                    .eq(ReasourceOpenEntity::getCreatePersonCode, user.getUserCode())
                    .eq(ReasourceOpenEntity::getOpenType, 4));
            isOk = reasourceOpenService.removeById(reasourceOpenServiceOne.getId());
        }
        ReasourceEntity reasourceEntity = this.getOne(Wrappers.<ReasourceEntity>lambdaQuery()
                .eq(ReasourceEntity::getReasourceCode, reasourcePo.getReasourceCode()));
        CollectorEntity collectorEntity = new CollectorEntity();
        collectorEntity.setUserCode(user.getUserCode());
        collectorEntity.setUserName(user.getUserName());
        collectorEntity.setName(reasourceEntity.getRName());
        collectorEntity.setCode(reasourcePo.getReasourceCode());
        collectorEntity.setImage(reasourceEntity.getImage());
        collectorEntity.setType(1);
        if (reasourcePo.getOpenType() == 4) {
            isOk = collectorService.saveCollector(collectorEntity);
        }
        if (reasourcePo.getOpenType() == 5) {
            isOk = collectorService.delete(collectorEntity);
        }
        return isOk;
    }


    /**
     * * 在给定的日期加上或减去指定月份后的日期
     * *
     * * @param sourceDate 原始时间
     * * @param month      要调整的月份，向前为负数，向后为正数
     * * @return
     */
    public static Date stepMonth(Date sourceDate, int month) {
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, month);
        return c.getTime();
    }

}
